<?php

namespace app\model;

use support\think\Model;

class Settings extends Model
{
    // 表名
    protected $name = 'lucky_settings';
    // 主键
    protected $pk = 'id';
    // 自动写入时间戳
    protected $autoWriteTimestamp = 'timestamp';

    /**
     * 获取所有设置，将key作为键名，value作为值，输出为一个数组
     * @return array 设置数组
     */
    public static function getAllSettings()
    {
        $settings = self::select();
        $result = [];

        foreach ($settings as $setting) {
            $result[$setting->key] = $setting->value;
        }

        return $result;
    }

    /**
     * 根据key获取单个设置值
     * @param string $key 设置键名
     * @param mixed $default 默认值
     * @return mixed 设置值
     */
    public static function getValue($key, $default = null)
    {
        $setting = self::where('key', $key)->find();
        return $setting ? $setting->value : $default;
    }

    /**
     * 设置单个配置项
     * @param string $key 设置键名
     * @param mixed $value 设置值
     * @return bool 是否成功
     */
    public static function setValue($key, $value)
    {
        $setting = self::where('key', $key)->find();

        if ($setting) {
            $setting->value = $value;
            return $setting->save();
        } else {
            $setting = new self();
            $setting->key = $key;
            $setting->value = $value;
            return $setting->save();
        }
    }

    /**
     * 批量设置配置项
     * @param array $settings 配置数组，格式为[key => value]
     * @return bool 是否成功
     */
    public static function setBatch($settings)
    {
        try {
            foreach ($settings as $key => $value) {
                self::setValue($key, $value);
            }
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }
}
